<template>
	<view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '/pages/store/user.js'

const userStore = useUserStore()

const loadingText = ref('')
const isLoading = ref(false)

const wxlogin = async () => {
  loadingText.value = '微信授权登录中...'

  try {
    isLoading.value = true
    
    // 获取微信登录凭证
    const loginResult = await new Promise((resolve) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          console.log('loginResult:', res);
          
          if (res.code) {
            resolve({ success: true, code: res.code })
          } else {
            resolve({ success: false, message: '获取登录凭证失败' })
          }
        },
        fail: (err) => {
          console.error('获取登录凭证失败:', err)
          resolve({ success: false, message: '获取登录凭证失败' })
        }
      })
    })

    if (!loginResult.success) {
      uni.showToast({
        title: loginResult.message || '登录失败',
        icon: 'none'
      })
      return
    }

    // 调用后端登录接口
    const serverLoginResult = await new Promise((resolve) => {
      console.log('loginResult.code:', loginResult.code);
      uni.request({
        url: 'https://www.dachen.vip/api/workflow/hooks/NjhhYzA0MWExM2JiZTE1YzY0ZDU3NzI4',
        method: 'POST',
        data: {
          code: loginResult.code,
		  type: 1
          // avatarUrl: avatarUrl.value,
          // nickname: nickname.value
        },
        success: (response) => {
          if (response) {

            resolve({
              success: true,
              message: '登录成功',
              data: response.data
            })
          } else {
            resolve({
              success: false,
              message: response.data.message || '服务器登录失败'
            })
          }
        },
        fail: (error) => {
          console.error('服务器登录失败:', error)
          resolve({
            success: false,
            message: '网络错误，请检查网络连接'
          })
        }
      })
    })

    
    console.log('serverLoginResult', serverLoginResult);

    if (serverLoginResult.success) {
   
     const apiUserInfo = JSON.parse(serverLoginResult.data.data)
     console.log('apiUserInfo', apiUserInfo);

         uni.request({
        url: 'https://www.dachen.vip/api/workflow/hooks/NjhlNzNmZTk3MTNmODU1M2IyNDZlMTU4',
        method: 'POST',
        data: {
          userRowid: apiUserInfo.rowid,
        }
        })
     
      // 将用户信息存储到本地
      uni.setStorageSync('userInfo', apiUserInfo)
      // 登录成功，保存用户信息
      userStore.setRowid(apiUserInfo.rowid)
        userStore.userInfo = apiUserInfo
        userStore.isLogin = true


      // 延迟跳转
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/tabs/profile/myProfile?from=qrcode'
        })
      }, 1500)
    } else {
      uni.showToast({
        title: serverLoginResult.message || '登录失败',
        icon: 'none'
      })
    }
    
  } catch ( error) {
    console.error('登录错误:', error)
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

onLoad(() => {
	console.log('二维码页面加载完成');
	wxlogin()

})	
	
</script>

<style>
	       
</style>
